package de.wefunkdroid.core;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

public class BitmapManager {
	Context ctx;
	HashMap<String, String> savedBitmaps;
	private String sdPath;
	private final String appFolder = ".wedroid";

	private static BitmapManager instance;

	private BitmapManager(Context ctx) {
		this.ctx = ctx;
		sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
		if (!sdPath.endsWith("/")) {
			sdPath += "/";

		}
		sdPath += appFolder + "/";
		new File(sdPath).mkdirs();
		savedBitmaps = new HashMap<String, String>();
		File base = new File(sdPath);
		if (base.exists() && base.isDirectory()) {
			Log.d(BitmapManager.class.getSimpleName(), "userdir gefunden!!;-)");
			String[] filenames = base.list(new FilenameFilter() {

				@Override
				public boolean accept(File dir, String filename) {
					if (filename.endsWith(".jpg"))
						return true;
					else
						return false;
				}
			});
			if (filenames != null)
				;
			for (int i = 0; i < filenames.length; i++) {

				filenames[i] = filenames[i].replaceAll(".jpg", "");
				savedBitmaps.put(filenames[i], sdPath + filenames[i] + ".jpg");

			}

		}

	}

	public Bitmap loadbitmap(String stationNumber) {
		Bitmap erg = null;
		if (savedBitmaps.containsKey(stationNumber)) {
			try {
				BufferedInputStream bis = new BufferedInputStream(
						new FileInputStream(savedBitmaps.get(stationNumber)));
				erg = BitmapFactory.decodeStream(bis);
				bis.close();
			} catch (Exception e) {
				Log.e(getClass().getSimpleName(), "Error", e);

			}
		} else {
			try {
				new File(sdPath + stationNumber + ".jpg").createNewFile();
				URLConnection con = new URL(WefunkStatics.getInstance(ctx)
						.getBitmapLink(stationNumber)).openConnection();
				BufferedOutputStream bos = new BufferedOutputStream(
						new FileOutputStream(new File(sdPath + stationNumber
								+ ".jpg")));
				BufferedInputStream fbis = new BufferedInputStream(con
						.getInputStream());
				byte[] databuffer = new byte[4096];
				int bytesread = 0;
				while ((bytesread = fbis.read(databuffer, 0, 4096)) != -1) {
					bos.write(databuffer, 0, bytesread);
				}
				fbis.close();
				bos.close();
				fbis = new BufferedInputStream(new FileInputStream(new File(
						sdPath + stationNumber + ".jpg")));
				erg = BitmapFactory.decodeStream(fbis);
				fbis.close();
				savedBitmaps
						.put(stationNumber, sdPath + stationNumber + ".jpg");

			} catch (Exception e) {
				Log.e(getClass().getSimpleName(), "Error", e);

			}

		}
		erg = erg.copy(erg.getConfig(), true);
		return erg;
	}

	public static BitmapManager getInstance(Context ctx) {
		if (instance == null)
			instance = new BitmapManager(ctx);
		return instance;
	}

}
